package com.ewhale.feitengguest.ui.auth

import android.os.Bundle
import android.os.CountDownTimer
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import butterknife.BindView
import butterknife.OnClick
import com.ewhale.feitengguest.R
import com.ewhale.feitengguest.dto.LoginInfoDto
import com.ewhale.feitengguest.presenter.user.auth.BindAccountPresenter
import com.ewhale.feitengguest.ui.shop.ShopMainActivity.Companion.open
import com.ewhale.feitengguest.ui.user.MainActivity
import com.ewhale.feitengguest.utils.Contants
import com.ewhale.feitengguest.utils.PickerUtils
import com.ewhale.feitengguest.utils.UserInfoUtils.saveLoginUserInfo
import com.ewhale.feitengguest.view.auth.BindAccountView
import com.orhanobut.hawk.Hawk
import com.simga.library.activity.MBaseActivity
import com.simga.library.utils.CheckUtil
import com.simga.library.utils.HawkKey
import com.simga.library.utils.StringUtil
import com.simga.library.widget.BGButton
import kotlinx.android.synthetic.main.activity_bind_account.*

class BindAccountActivity : MBaseActivity<BindAccountPresenter?>(), BindAccountView
/**, TextWatcher */
{
    private var isPwdShow = false
    private var isPwd2Show = false
    private var type = 0
    private var currentTabTitle: String? = null

    override fun onGetBundle(bundle: Bundle) {
        type = bundle.getInt("type")
        currentTabTitle = bundle.getString("currentTabTitle")
    }

    override fun getViewId(): Int {
        return R.layout.activity_bind_account
    }

    override fun init(savedInstanceState: Bundle?) {
        setTitle("绑定手机号码")
        if (currentTabTitle == "我是商家") {
            et_invite.visibility = View.INVISIBLE
            tv_regist.visibility = View.VISIBLE
        }
    }

    override fun isUseBaseTitleBar(): Boolean {
        return true
    }

    override fun initListener() {
//        et_regist_phone.addTextChangedListener(this);
//        et_regist_phone.addTextChangedListener(this);
//        et_registe_password.addTextChangedListener(this);
//        et_registe_password_again.addTextChangedListener(this);
//        et_code.addTextChangedListener(this);
        tv_regist.setOnClickListener {
            PickerUtils.getInstance().pickerOption(mContext, "请选择商家类型", arrayOf("个人", "企业")) { index, item -> tv_regist!!.text = item }
        }
    }

    override fun showProLoading() {
        showLoading()
    }

    override fun dimissProLoading() {
        dismissLoading()
    }

    override fun showErrorMessage(postCode: Int, code: String, message: String) {
        showErrorMsg(code, message)
    }

    @OnClick(R.id.btn_getcode, R.id.iv_eye1, R.id.iv_eye2, R.id.btn_bindPhone)
    fun onViewClicked(view: View) {
        val phone: String
        val code: String
        val registerPwd: String
        val registerPwd2: String
        val inviteCode: String
        when (view.id) {
            R.id.btn_getcode -> {
                phone = et_regist_phone!!.text.toString()
                when {
                    CheckUtil.isNull(phone) -> showToast("请输入手机号码")
                    !StringUtil.isMobile(phone) -> showToast("请输入正确手机号码")
                    else -> presenter!!.getCode(if (currentTabTitle != "我是商家") Hawk.get(HawkKey.USER_AUTHENTICATION, "") else Hawk.get(HawkKey.SHOP_AUTHENTICATION, ""), phone)
                }
            }
            R.id.iv_eye1 -> {
                et_registe_password!!.transformationMethod = if (isPwdShow) PasswordTransformationMethod.getInstance() else HideReturnsTransformationMethod.getInstance()
                iv_eye1!!.setImageResource(if (isPwdShow) R.mipmap.a_icon_eyes_n else R.mipmap.a_icon_eyes_s)
                isPwdShow = !isPwdShow
            }
            R.id.iv_eye2 -> {
                et_registe_password_again!!.transformationMethod = if (isPwd2Show) PasswordTransformationMethod.getInstance() else HideReturnsTransformationMethod.getInstance()
                iv_eye2!!.setImageResource(if (isPwd2Show) R.mipmap.a_icon_eyes_n else R.mipmap.a_icon_eyes_s)
                isPwd2Show = !isPwd2Show
            }
            R.id.btn_bindPhone -> {
                phone = et_regist_phone!!.text.toString()
                code = et_code!!.text.toString()
                registerPwd = et_registe_password!!.text.toString()
                registerPwd2 = et_registe_password_again!!.text.toString()
                inviteCode = et_invite!!.text.toString()
                when {
                    CheckUtil.isNull(phone) -> showToast("请输入手机号码")
                    !StringUtil.isMobile(phone) -> showToast("请输入正确手机号码")
                    CheckUtil.isNull(code) -> showToast("请输入验证码")
                    !CheckUtil.checkEqual(registerPwd, registerPwd2) -> showToast("两次密码不同，请重新确认密码")
                    currentTabTitle == "我是商家" && CheckUtil.isNull(tv_regist!!.text.toString()) -> showToast("请选择个人注册或者是企业注册")
                    else -> {
                        presenter!!.bindPhone(if (currentTabTitle == "我是商家") 1 else 0, phone, code, registerPwd, if (currentTabTitle == "我是商家") tv_regist!!.text.toString() else inviteCode)
                    }
                }
            }
        }
    }

    override fun getCodeSuccess() {
        showToast("验证码已发送，请注意查收")
        mTimer.start()
    }

    override fun bindPhoneSuccess(result: LoginInfoDto) {
        showToast("登录成功")
        saveLoginUserInfo(currentTabTitle!!,result)
        Hawk.put(HawkKey.LOGIN_THIRD_TYPE, (if (type == 1) Contants.weChat else Contants.qq))
        if (currentTabTitle!! == "我是用户") { //普通用户
            MainActivity.open(mContext)
        } else { //商家
            open(mContext)
        }
        //        new Handler().postDelayed(() -> {
//            showLoading();
//            AuthHelper.getInstance().login(mContext, result.getHxId(), result.getHxPassword(), new AuthHelper.AuthCallback() {
//                @Override
//                public void onSuccess() {
//                    dismissLoading();
//                    showToast("登录成功");
////                        HttpHelper.authentication = result.getSessionId();
//                    Hawk.put(HawkKey.USER_HX_ID, result.getHxId());
//                    Hawk.put(HawkKey.USER_HX_PASSWORD, result.getHxPassword());
//                    Hawk.put(HawkKey.USER_AVATAR, result.getHeadPhoto());
//                    Hawk.put(HawkKey.USER_NICK_NAME, result.getNickName());
//                    Hawk.put(HawkKey.USER_AUTHENTICATION, result.getSessionId());
//                    Hawk.put(HawkKey.USER_PHONE, result.getPhone());
//                    Hawk.put(HawkKey.IS_USER_LOGIN, true);
//                    Hawk.put(HawkKey.USER_LOGIN_INFO, result);
//                    if (type == 1) {
//                        Hawk.put(HawkKey.LOGIN_THIRD_TYPE, Contants.weChat);
//                    } else {
//                        Hawk.put(HawkKey.LOGIN_THIRD_TYPE, Contants.qq);
//                    }
//                    finishResult();
//                }
//
//                @Override
//                public void onError(int errorCode, String errorStr) {
//                    dismissLoading();
//                    showToast("环信登录失败，请联系环信管理员");
//                }
//            });
//        }, 500);
    }

    private val mTimer: CountDownTimer = object : CountDownTimer(60 * 1000, 1000) {
        override fun onTick(millisUntilFinished: Long) {
            btn_getcode!!.run {
                text = (millisUntilFinished / 1000).toString() + "s"
                setTextColor(ContextCompat.getColor(mContext, R.color.text_666666))
                isEnabled = false
                setNormalSolid(ContextCompat.getColor(mContext, R.color.default_window_color))
                setNormalStroke(1, ContextCompat.getColor(mContext, R.color.default_window_color))
            }
        }

        override fun onFinish() {
            btn_getcode!!.run {
                setTextColor(ContextCompat.getColor(mContext, R.color.main_color))
                isEnabled = true
                setNormalSolid(ContextCompat.getColor(mContext, R.color.white))
                setNormalStroke(1, ContextCompat.getColor(mContext, R.color.main_color))
            }
        }
    }
    //    @Override
    //    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    //    }
    //
    //    @Override
    //    public void onTextChanged(CharSequence s, int start, int before, int count) {
    //        if (!checkInput()) {
    //            btn_bindPhone.setNormalSolid(Color.parseColor("#EEEEEE"));
    //            btn_bindPhone.setNormalStroke(1, Color.parseColor("#D4D4D4"));
    //            btn_bindPhone.setTextColor(Color.parseColor("#BBBBC2"));
    //        } else {
    //            btn_bindPhone.setNormalSolid(ContextCompat.getColor(mContext, R.color.main_color));
    //            btn_bindPhone.setNormalStroke(1, ContextCompat.getColor(mContext, R.color.main_color));
    //            btn_bindPhone.setTextColor(Color.parseColor("#ffffff"));
    //        }
    //    }
    //
    //    @Override
    //    public void afterTextChanged(Editable s) {
    //    }
    /**
     * 检查输入框
     *
     * @return
     */
    fun checkInput(): Boolean {
        return !(CheckUtil.isNull(et_regist_phone!!.text.toString()) ||
                CheckUtil.isNull(et_code!!.text.toString()) ||
                CheckUtil.isNull(et_registe_password!!.text.toString()) ||
                CheckUtil.isNull(et_registe_password_again!!.text.toString()))
    }

    companion object {
        @JvmStatic
        fun open(context: MBaseActivity<*>, type: Int, currentTabTitle: String?) {
            val bundle = Bundle()
            bundle.putInt("type", type)
            bundle.putString("currentTabTitle", currentTabTitle)
            context.startActivity(bundle, BindAccountActivity::class.java)
        }
    }
}